interface StorageItem {
  value: any;
  invalidTime: number;
}

class _Storage {
  private storage: Storage;

  constructor() {
    this.storage = localStorage;
  }

  public get(key: string) {
    const item = this.storage.getItem(key);
    if (!item) {
      return undefined;
    }
    const storageItem: StorageItem = JSON.parse(item);
    if (storageItem.invalidTime < 0 || Date.now() < storageItem.invalidTime) {
      return storageItem.value;
    }
    this.storage.removeItem(key);
    return undefined;
  }

  public set(key: string, value: any, duration?: number) {
    const storageItem = { value, invalidTime: Date.now() };
    if (duration && duration > 0) {
      storageItem.invalidTime += duration;
    } else {
      storageItem.invalidTime = -1;
    }
    this.storage.setItem(key, JSON.stringify(storageItem));
  }

  public clear() {
    this.storage.clear();
  }

  public remove(key: string) {
    this.storage.removeItem(key);
  }
}

export const StorageKey = { KEY_INFO: 'KEY_INFO', TOKEN: 'TOKEN' };
export default new _Storage();
